
import { Component, OnInit, ElementRef, AfterViewInit, ViewChild } from '@angular/core';
import { DxDataGridComponent } from 'devextreme-angular';
import 'rxjs/add/operator/map';
import { Subject } from 'rxjs/Rx';
import { Observable } from 'rxjs/Rx';

import { CommService } from '../../comm/comm.service';
import { ReportUrls } from '../../comm/report.urls.conf';
import { SAT } from '../../model/report/sat';
import { SubArea } from '../../model/report/sub-area';
import { Resource } from '../../model/report/resource';
import { QueryModel } from '../../model/report/query-model';
import { ResponseModel } from '../../model/comm/response-model';
import { ChartOptionCreater } from '../../model/comm/chart-option-creater';
import * as c3 from 'c3';
import 'rxjs/add/operator/toPromise';
declare const $: any;
import * as moment from 'moment';
declare var swal: any;
import * as Enumerable from 'linq';
import { TVResource } from 'app/ptpmc/model/comm/tv-resource';
import { DxDropDownBoxComponent } from 'devextreme-angular';
@Component({
    selector: 'app-report-sat',
    templateUrl: './sat.component.html',
    styleUrls: ['./sat.component.scss']
})



export class SATComponent implements OnInit {
    public saaList: SAT[];
    public saaGroupList: SAT[];
    public saaStationGroupList: SAT[];
    //界面显示数据定义
    public saaChartOption: any;
    public saaStationChartOption: any;
    public minValue = 0;
    constructor(private commServices: CommService) {
    }
    //组件初始化
    ngOnInit() {
        this.commServices.initDatePicker($('#DateTimeRange'), 'YYYY-MM-DD');
        this.shiftItems = this.commServices.shifts;
        this.shiftSelected = this.shiftItems[0];
        this.subAreaItems = this.commServices.getSubAreas();
        this.subAareSelected = this.subAreaItems[0];
        this.equipemntItems = this.commServices.getTVResourceBySubArea(this.subAreaItems[0].subArea);
        //this.equipemntItems = this.equipemntItems.filter((item:any) => item.saaAnalyse === 1);
        this.equipmentSelected = this.equipemntItems;
        //this.showTIPTopGrid();
    }

    showloading = true;

    /*生产线 - 班次*/
    public subAreaItems: SubArea[];
    public shiftItems: any[];
    public equipemntItems: TVResource[] = [];

    public subAareSelected: any;
    public shiftSelected: any;
    public equipmentSelected: TVResource[] = [];
    @ViewChild('dddb') dddb: DxDropDownBoxComponent;
    clearEquipmentSelected() {
        this.equipmentSelected = [];
    }
    equipmentSelectedOk() {
        this.dddb.instance.close();
    }
    onSubAreaSelectedChange(subArea: any): void {
        //this.equipmentSelected = [];
        this.equipemntItems = this.commServices.getTVResourceBySubArea(subArea.value.subArea);
       // this.equipemntItems = this.equipemntItems.filter((item:any) => item.saaAnalyse === 1);
        this.equipmentSelected = this.equipemntItems;
    }
    /**
     * 获取表格数据
     */
    getReportData(): void {
        const queryModel: QueryModel = new QueryModel();
        queryModel.dateTimeRange = this.getTime('DateTimeRange');
        queryModel.querySubAreaIds = [this.subAareSelected.subArea];
        queryModel.queryResourceIds = this.equipmentSelected.map(e => e.resource);
        //queryModel.minValue = this.minValue;
       debugger

        this.commServices
            .getList(queryModel, ReportUrls.SATUrl)
            .subscribe(model => {
                if (model.resultCode === 200) {
                    debugger
                    this.saaList = model.data;
                    this.getSAAGroupList();
                    this.showSAAChart();
                   
                } else {
                    console.log(model.resultCode + ',' + model.resultMessage);
                }
            });
    }
    private getSAAGroupList() {
        this.saaGroupList = Enumerable.from(this.saaList).groupBy(u => u.resource)
            .select(u => {
                debugger
                const temp: SAT = new SAT();
                temp.resource = u.first().resource;
                temp.subArea = u.first().subArea;
                temp.stationCode = u.first().stationCode;
                temp.productDate = u.first().productDate;
                temp.equipment = u.first().equipment;
               const i =  u.sum(item=>item.totCt);
               const j =  u.count()
               debugger
                temp.totCt = Number.parseFloat(u.average(item => item.totCt).toFixed(2));
                temp.totDown = Number.parseFloat(u.average(item => item.totDown).toFixed(2));
                temp.minValue = this.minValue;
                temp.SAT = temp.totCt/(temp.totCt+temp.totDown)*temp.minValue;
                return temp;
            }).orderBy(u => u.equipment).toArray();
    }

    /**
     * 获取TimeRange的值
     * @param id id
    */
    getTime(id: any): String {
        const timerange: String = $('#' + id).val();
        return timerange;
    }
    /**ECharts图表相关*/
    chartsMap = new Map<number, any>();
    onChartInit(index: number, echartsIntance: any): void {
        this.chartsMap.set(index, echartsIntance);
        Observable.fromEvent(window, 'resize')
            .debounceTime(100) // 以免频繁处理
            .subscribe((event) => this.chartsMap.forEach((v, k) => v.resize()));
    }

    selectedIndexChange(tabIndex: any) {
        this.chartsMap.get(tabIndex).resize();
    }
    private showSAAChart(): void {
        const xData = new Array();
        const list = new Array();
     
        const series = new Array();
        this.saaGroupList.forEach(u => {
            const station = u.equipment;
            xData.push(station);
            list.push(u.SAT);
           
        });
        series.push(
            {
                name: 'SAT',
                type: 'bar',
                data: list,
                itemStyle: {
                    normal: {
                        color: '#63B8FF'
                    },
                },
            }
        )
        
        const legend = ['GrossJPH', 'SAA JPH', '目标JPH'];
        this.saaChartOption = ChartOptionCreater
            .createChartsOption('', '', '', '', legend, xData, series, null); // SAA分析（按设备分）Throughput (JPH)
        // this.showloading = false;
    }

  
  

    protected exportData() {
        const files = new Array<any>();
        const queryModelArray = new Array<any>();

        const tables = new Array<any>();

        const row1 = new Array();
        // this.saaGroupList.forEach((e: SAA) => {
        //     const co = new Array();
        //     co.push(e.subArea);
        //     co.push(e.equipment);
        //     co.push(e.totCT);
        //     co.push(e.downTime);
        //     co.push(e.actualCT);
        //     co.push(e.targetCT);
        //     co.push(e.perSAA);
        //     co.push(e.grossJPH);
        //     co.push(e.saajph);
        //     co.push(e.targetJPH);
        //     row1.push(co);
        // });
        // const table1 = {
        //     tableName: 'SAA分析按设备查询',
        //     titles: ['区域', '设备', 'Total Cycle', '停机时间', '实际平均节拍', '规划节拍', 'SAA%', 'Gross JPH', 'SAA JPH', '目标 JPH'],
        //     rows: row1
        // };

        // const row2 = new Array();
        // this.saaStationGroupList.forEach((e: SAA) => {
        //     const co = new Array();
        //     co.push(e.subArea);
        //     co.push(e.stationCode);
        //     co.push(e.grossJPH);
        //     co.push(e.saajph);
        //     co.push(e.targetJPH);
        //     row2.push(co);
        // });
        // const table2 = {
        //     tableName: 'SAA分析按设工位查询',
        //     titles: ['区域', '工位', 'Gross JPH', 'SAA JPH', '目标 JPH'],
        //     rows: row2
        // };

        // tables.push(table1);
        // tables.push(table2);

        queryModelArray.push('时间:' + this.getTime('DateTimeRange'));
        queryModelArray.push('区域:' + this.subAareSelected.subArea);
        let resourceStr = '';
        this.equipmentSelected.map(e => e.equipment).forEach(e => {
            resourceStr += e + ',';
        });
        queryModelArray.push('设备:' + resourceStr);
        queryModelArray.push('班次:' + (this.shiftSelected.shiftId === '-1' ? '全部' : this.shiftSelected.shiftId === '1' ? '早班' : '中班'));
        this.chartsMap.forEach((v, k) => {
            const picBase64Info = v.getDataURL();
            files.push({ chartsTitle: k, chartsEncodeStr: picBase64Info });
        });

        const upload = {
            reportTitle: 'SAA分析',
            charts: files,
            queryModel: queryModelArray,
            tables: tables
        };

        this.commServices.exportPdf(upload);
    }
}